package qeb.handheldmedical.approval;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import qeb.handheldmedical.Home;
import qeb.handheldmedical.Login;
import qeb.handheldmedical.R;
import qeb.handheldmedical.adapter.ApprovalOperationAdapter;
import qeb.handheldmedical.dialog.MultiDialog;
import qeb.handheldmedical.helper.WSHelper;
import qeb.handheldmedical.model.User;
import android.app.Activity;
import android.content.Intent;
import android.net.http.SslCertificate;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;

/**
 * @author 作者(dugaoyi) E-mail:dugaoyi@163.com
 * @version 创建时间：2016年10月20日 下午3:20:52
 * @declaration 审批手术病人
 */
public class ApprovalOperationPatients extends Activity {
	private ExpandableListView lvSsPatients;
	private MultiDialog mDialog;
	User usr = new User();
	private static final int UPDATE = 0;
	private String splx;
	private JSONArray jsonArray;
	private ApprovalOperationAdapter adapter;
	Button btn_title_back, btn_title_right;
	private TextView tv_top_title;
	private String ssid;
	private MultiDialog checkdialog;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.approval_operation_patients);
		usr = (User) getIntent().getSerializableExtra("userinfo");
		splx = getIntent().getStringExtra("splx");
		initUI();
		mDialog = new MultiDialog(ApprovalOperationPatients.this,
				MultiDialog.DialogType.WAITING);
		mDialog.setMessage("正在加载，请稍候......");
		mDialog.show();
		new Thread() {

			@Override
			public void run() {
				try {
					getData();
					myHandler.sendEmptyMessage(UPDATE);
				} catch (Exception e) {
					// TODO: handle exception
					// Log.v("LineExam", e.toString());
				}
			}
		}.start();
	}

	/**
	 * 读取数据
	 */
	protected void getData() {
		// TODO Auto-generated method stub
		jsonArray = null;
		if (usr.BQID != null) {
			Map<String, String> map = new HashMap<String, String>();
			// 未审核
			if (splx.equals("0")) {
				map.put("Sszt", "0");
			} else {
				map.put("Sszt", "1,2,3");
			}
			map.put("Sslb", "1,2");
			if (splx.equals("2")) {
				map.put("Ylz", usr.YLZ);
			} else {
				map.put("Ylz", "");
			}
			if (splx.equals("3")) {
				map.put("bqid", usr.BQID);
			} else {
				map.put("bqid", usr.BQID);
			}
			map.put("SqSsj", "");
			map.put("SqsjEnd", "");
			map.put("did", "");
			jsonArray = WSHelper.getWebserviceFun("GetSstzd", map);
		}
	}

	/**
	 * 加载UI
	 */
	private void initUI() {
		// TODO Auto-generated method stub
		lvSsPatients = (ExpandableListView) findViewById(R.id.lvSsPatients);
		btn_title_back = (Button) findViewById(R.id.btn_title_back);
		btn_title_back.setOnClickListener(MyOnClickListener);
		btn_title_right = (Button) findViewById(R.id.btn_title_right);
		btn_title_right.setOnClickListener(MyOnClickListener);
		tv_top_title = (TextView) findViewById(R.id.tv_top_title);
		if (splx.equals("0")) {
			tv_top_title.setText("手术审批（未审批）");
		} else if (splx.equals("1")) {
			tv_top_title.setText("手术审批（已审批）");
		} else if (splx.equals("2")) {
			tv_top_title.setText("手术查询（本组）");
		} else if (splx.equals("3")) {
			tv_top_title.setText("手术查询（病区）");
		}
	}

	Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE:
				bandList();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
			// isRunning=false;
			mDialog.cancel();
		}
	};
	private OnClickListener MyOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			switch (v.getId()) {
			// 退回
			case R.id.btn_title_back:
				ApprovalOperationPatients.this.finish();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 绑定数据
	 */
	private void bandList() {
		// TODO Auto-generated method stub
		lvSsPatients.setVisibility(View.VISIBLE);
		if (jsonArray != null && jsonArray.length() > 0) {
			adapter = new ApprovalOperationAdapter(
					ApprovalOperationPatients.this, jsonArray);
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
			lvSsPatients.setAdapter(adapter);
			lvSsPatients.expandGroup(0);
			// 未审批
			if (splx.equals("0")) {
				lvSsPatients
						.setOnChildClickListener(new OnChildClickListener() {

							@Override
							public boolean onChildClick(
									ExpandableListView parent, View v,
									int groupPosition, int childPosition,
									long id) {
								// TODO Auto-generated method stub
								JSONObject tzd = null;
								ssid = "";
								try {
									tzd = jsonArray
											.getJSONObject(groupPosition);
									ssid = tzd.getString("AUTOID");
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									ssid = "";
								}
								if (!ssid.equals("")) {
									checkdialog = new MultiDialog(
											ApprovalOperationPatients.this,
											MultiDialog.DialogType.CONFIRM);
									checkdialog.setTitle("手术审批确认");
									checkdialog
											.setMessage("该操作将手术通过审批，是否确定继续？");
									checkdialog
											.setDialogGoListener(new OnClickListener() {
												@Override
												public void onClick(View arg0) {
													// TODO Auto-generated
													// method stub
													checkdialog.cancel();
													HashMap<String, String> map = new HashMap<String, String>();
													map.put("autoid", ssid);
													map.put("userid", usr.DID);
													map.put("username",
															usr.DNAME);
													map.put("sqdzt", "1");

													JSONArray jsonResult = WSHelper
															.getWebserviceFun(
																	"SetSsSqd",
																	map);

													JSONObject result = null;

													try {
														result = jsonResult
																.getJSONObject(0);
														if (result
																.getString(
																		"pda_error_state")
																.equals("0")) {

															getData();
															bandList();
														}
														Toast tt = Toast
																.makeText(
																		ApprovalOperationPatients.this,
																		result.getString("pda_error_message"),
																		Toast.LENGTH_LONG);
														tt.show();
														tt.setGravity(
																Gravity.CENTER,
																0, 0);
													} catch (JSONException e) {
														// TODO Auto-generated
														// catch block
														e.printStackTrace();
													}

												}
											});
									checkdialog.show();
								} else {
									checkdialog = new MultiDialog(
											ApprovalOperationPatients.this,
											MultiDialog.DialogType.ALERT);
									checkdialog.setTitle("系统提醒");
									checkdialog.setMessage("操作失败！");
									checkdialog.show();
								}
								return true;
							}
						});

			}
		} else {
			lvSsPatients.setVisibility(View.GONE);
		}
	}
}
